package com.crm.controller.sourceController;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.crm.dao.OpportunityDAO;
import com.crm.dao.PartSourcesDAO;
import com.crm.dao.SourceInfoDAO;
import com.crm.dao.SourcesDAO;
import com.crm.dao.SupplierDAO;
import com.crm.entity.Business;
import com.crm.entity.Opportunity;
import com.crm.entity.PartSources;
import com.crm.entity.Parts;
import com.crm.entity.SourceInfo;
import com.crm.entity.Supplier;
import com.crm.util.Constants;



@Controller
@RequestMapping("/importsource")
public class ImpFromSrcController {
	protected final Log logger = LogFactory.getLog(getClass());
	@RequestMapping( "/show.do") 
	public ModelAndView show(HttpServletRequest request,HttpSession session, ModelAndView model) throws Exception{
		try{
			Business bus=(Business)session.getAttribute("business");
			if(bus==null)return new ModelAndView("/jsp/index.jsp");
			//OpportunityDAO oprD=new OpportunityDAO();
			List<Opportunity> opr=null;
			try{
				opr=(List<Opportunity>)OpportunityDAO.getSingleInstance().getAllEnqSources(bus.getBusinessId());
					logger.info("opportunity list is "+opr);
			}catch(NullPointerException e){
				e.printStackTrace();
			}
			
		
			  model = new ModelAndView("/jsp/ImportFromSource.jsp");
				model.addObject("opprtunity",opr);
				model.addObject("submenu", "sourcingInfo");
				model.addObject("menuName","sourcingInfo");
				if(request.getAttribute("sources")!=null){
					model.addObject("sources",request.getAttribute("sources"));
					System.out.println("From Export To Source Controller:"+request.getAttribute("sources"));
				}
				return model;
		}catch(Exception e){
			System.out.println("An Exceoption Occured When Importing from source in show.do");
			e.printStackTrace();
			return model;
		}
	}
	@RequestMapping( "/search.do") 
	public ModelAndView search(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		try {
			Business bus=(Business)session.getAttribute("business");
			if(bus==null)return new ModelAndView("/jsp/index.jsp");
			String ref=req.getParameter("reflist");
			logger.info("refno is "+ref);
			return null;
		} catch (Exception e) {
			System.out.println("An Exception Occured In Import from source controller in search.do");
			e.printStackTrace();
			return model;
		}
	}
	@RequestMapping("/getsource.do")
	public @ResponseBody String getDiv(HttpServletRequest req,HttpSession session,ModelAndView model) throws Exception{
		try {
			Business bus=(Business)session.getAttribute("business");
			System.out.println("Running X00001 ");
			String enqno=req.getParameter("refno");
			int busid=bus.getBusinessId();
			logger.info("refrence no is "+enqno);
			PartSourcesDAO prtDAO=new PartSourcesDAO();
			List<String> slist=null;
			//OpportunityDAO oppdao=new OpportunityDAO();
			Opportunity opp=OpportunityDAO.getSingleInstance().getByRef(enqno, busid);
			StringBuilder sourcelist= new StringBuilder();
			try {
				slist=prtDAO.getPartSources(opp.getId(), busid);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("the source list is "+sourcelist);
			if (slist!=null) {
				for(int i=0;i<slist.size();i++){
					String sname =slist.get(i);
				System.out.println("the source name  is " + sname);
					sourcelist.append("," + sname);
				}
			}
			sourcelist.append("@"+opp.getOrganisation()+","+opp.getDivision()+","+opp.getUser());
			System.out.println("the list of sources is "+sourcelist);
			return sourcelist.toString();
		} catch (Exception e) {
			System.out.println("An Exception occured in import from source controller in getsource.do ");
			e.printStackTrace();
			return null;
		}
		
	}
	@RequestMapping( "/getparts.do") 
	public ModelAndView getParts(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		try {
			Business bus=(Business)session.getAttribute("business");
			String ref=req.getParameter("refno");
			String srcname=req.getParameter("sourceName");
			logger.info("refno is "+ref);
			logger.info("source name in getparts  "+srcname);
			logger.info("hello we are in Getparts method");
			SourceInfoDAO siDAO= new SourceInfoDAO();
			List<Parts> partlist=null;
			if(!"Select".equalsIgnoreCase(ref.trim())&&!"SourceNot Exist".equalsIgnoreCase(srcname.trim())){
			partlist=siDAO.getPartsNo(srcname, ref,bus.getBusinessId());
			}
			//OpportunityDAO op=new OpportunityDAO();
			Opportunity o=OpportunityDAO.getSingleInstance().getByRef(ref,bus.getBusinessId());
			
			SupplierDAO supDAO=new SupplierDAO();
			List<Supplier> spl = null;
			spl=supDAO.findAll(bus.getBusinessId());
			model = new ModelAndView("/jsp/ImportSourceRes.jsp");
			model.addObject("partlist",partlist);
			model.addObject("supplier",spl);
			model.addObject("clientdet",o.getOrganisation());
			model.addObject("division",o.getDivision());
			model.addObject("user",o.getUser());
			model.addObject("submenu", "sourcingInfo");
			model.addObject("menuName","sourcingInfo");
			return model;
		} catch (Exception e) {
			System.out.println("An Exception occured in import from source controller in getparts.do");
			e.printStackTrace();
			return model;
		}
	}
	@RequestMapping( "/importsave.do") 
	public ModelAndView importsave(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		try {
			Business bus=(Business)session.getAttribute("business");
			if(bus==null)return new ModelAndView("/jsp/index.jsp");
			int busid=bus.getBusinessId();
			String ref=req.getParameter("reflist");		
			String rowcount=req.getParameter("rowcount");
			String srcname=req.getParameter("srdiv");
			System.out.println("RowCount Is:"+rowcount);
			logger.info("refno is "+ref);
			//OpportunityDAO oprDAO=new OpportunityDAO();
			int rid=OpportunityDAO.getSingleInstance().getByRefNo(busid,ref.trim()).getId();
			Opportunity o=OpportunityDAO.getSingleInstance().getByRefNo(bus.getBusinessId(),ref);
			logger.info("The Column count is"+rowcount);
			List<SourceInfo> siLst=null;
			int srid=0;
			int rcount=Integer.parseInt(rowcount.trim());
			siLst=new ArrayList<SourceInfo>();


			for (int i=1; i <=rcount; i++){
				String partNo=req.getParameter("partno"+i);
				String partId=req.getParameter("partid"+i);
				logger.info("the part value is"+partNo);
				String desc=req.getParameter("desc"+i);
				if(partNo==null&&desc==null)
					continue;
				String reqqty=req.getParameter("rqty"+i);
				System.out.println("the req qty value is"+reqqty);
				int rqty=Integer.parseInt(reqqty.trim());
				String price=req.getParameter("uprice"+i);
				logger.info("the price value is"+price.trim());
				float uprice=Float.parseFloat(price.trim());
				logger.info("the unit price of flaot value is"+uprice);
				String supplier=req.getParameter("supplier"+i);
				
				String currency=req.getParameter("currency"+i);
				String aqty=req.getParameter("qtyable"+i);
				int availQty=Integer.parseInt(aqty.trim());
				logger.info("the qty value is"+availQty);
				String smoq=req.getParameter("moq"+i);
				int moq=Integer.parseInt(smoq.trim());
				String cond=req.getParameter("conditions"+i);;
				String make=req.getParameter("make"+i);
				
				String opn=req.getParameter("opartno"+i);
				System.out.println("Offering Part Number Is:"+opn);
				String sspq=req.getParameter("spq"+i);
				int spq=Integer.parseInt(sspq.trim());
				int pr= Integer.parseInt(partId);
				SourcesDAO sDAO=new SourcesDAO();
			
				srid = sDAO.getByName(srcname,bus.getBusinessId()).getId();
				SupplierDAO supDAO=new SupplierDAO();
				int splid=0;
					//Checking Whether Supplier Is Exists Or Not
					if(supplier!=null&&supplier.trim().length()>0){
						splid=supDAO.getByName(supplier,bus.getBusinessId()).getId();
						
					}
						String st=Constants.ST_SOURCE_INFO_PAR_IMPORT;
						rid=OpportunityDAO.getSingleInstance().getByRefNo(bus.getBusinessId(),ref).getId();
						try {
							OpportunityDAO.getSingleInstance().updateStatus(busid,st,rid);
						} catch (Exception e) {
						e.printStackTrace();
						}		
				
				logger.info("partNo "+partNo);
				logger.info("price "+price);
				logger.info("supplier "+supplier);		
				
				int requiredqty=Integer.valueOf(rqty);
				Float unitPrice = Float.valueOf(price);
				Integer availableQty = Integer.valueOf(availQty);
				Integer minordQty = Integer.valueOf(moq);
				SourceInfo si=null;
				if(srid!=0){
					 si=new SourceInfo(o.getId(),bus,uprice,spq,srid,splid,pr,requiredqty,unitPrice,currency,availableQty,minordQty,cond,make,opn);
					if((supplier!=null)&&(supplier.trim().length()>0))
					siLst.add(si);
				}
				System.out.println("Source Info Is:"+si);
			}
			//update PartSources and remove 
			PartSourcesDAO psDAO=new PartSourcesDAO();
			
			SourceInfoDAO srDAO=new SourceInfoDAO();
			srDAO.insertList(siLst);
			psDAO.updateSrc(rid,srid,bus.getBusinessId());
				
			List<PartSources> pslist=psDAO.getIsSrcCompleted(bus.getBusinessId(),rid);
			if(pslist.size()==0){
				String st=Constants.ST_SOURCE_INFO_RECEIVED;
				OpportunityDAO.getSingleInstance().updateStatus(bus.getBusinessId(),st,rid);
				//redirecting jsp for view basing srclist....
				model = new ModelAndView("redirect:/comparesource/show.do");
				model.addObject("msgsrc","Sucessfully Imported Source");
				model.addObject("currentref",ref);
					model.addObject("submenu", "sourcingInfo");
					model.addObject("menuName","sourcingInfo");
					return model;
					
			}
			else
			{
				model = new ModelAndView("redirect:/importsource/show.do");
				model.addObject("msgsrc","Sucessfully Imported for  Source named as "+srcname+"   ....Continue for More");
				model.addObject("currentref",ref);
				model.addObject("submenu", "sourcingInfo");
				model.addObject("menuName","sourcingInfo");
				return model;
			}
		} catch (Exception e) {
			System.out.println("An Exception occured in import from source controller in importsave.do");
			e.printStackTrace();
			return model;
		}
	}
	

	@RequestMapping( "/removesource.do") 
	public ModelAndView removesource(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		try {
			Business bus=(Business)session.getAttribute("business");
			if(bus==null)return new ModelAndView("/jsp/index.jsp");
			int busid=bus.getBusinessId();
			String ref=req.getParameter("refno");
			String srcname=req.getParameter("sourceName");
			logger.info("refno is "+ref);
			logger.info("source name in getparts  "+srcname);
			logger.info("hello we are in Getparts method");
			//OpportunityDAO oprDAO=new OpportunityDAO();
			int rid=OpportunityDAO.getSingleInstance().getByRefNo(busid,ref.trim()).getId();
			OpportunityDAO.getSingleInstance().removeRef(rid,bus.getBusinessId());
			model = new ModelAndView("redirect:/comparesource/show.do");
			model.addObject("msgsrc","Parts Are Sucessfully imported ...Now Compare The Prices");
			model.addObject("submenu", "sourcingInfo");
			model.addObject("menuName","admin");
			return model;
		} catch (Exception e) {
			System.out.println("An exception occured in import from source controller in removesource.do");
			e.printStackTrace();
			return model;
		}
	}

}